
var express = require('express');
var router = express.Router();
//  引入阿里IOT SDK
var iot = require('alibabacloud-iot-device-sdk');
var deviceInfo = {  // 设备ID
	ProductSecret: 'eDff6CtGXWKfFBz2t2ErZRkIqOEkAxkI',
	ProductKey:    'a1wlEo7ijKg',
	DeviceName:    'IDPkgFqBNLZFSJzYlhco',
	regionId: 'cn-shanghai-6',
}
// 一机一密设置
var device = iot.device({
  productKey: deviceInfo.ProductKey,      //将<productKey>修改为实际产品的ProductKey
  deviceName: deviceInfo.DeviceName,      //将<deviceName>修改为实际设备的DeviceName
  deviceSecret: deviceInfo.ProductSecret, //将<deviceSecret>修改为实际设备的DeviceSecret
});


// 连接设备
device.on('connect', () => {
	console.log('connect successfully!');
});

// 订阅指定topic
device.subscribe('/' + deviceInfo.ProductKey + '/' + deviceInfo.DeviceName +  '/user/get');
// 接收到数据时将topic以及消息打印出来
device.on('message', (topic, payload) => {
	console.log('message_topic = ', topic);
	console.log('message_payload = ', payload.toString());
});


// 树莓派
// var rpio = require('rpio');
// var LED_PIN = 29;  // 控制端口
// rpio.open(LED_PIN, rpio.OUTPUT,rpio.LOW);


// var rpio = require('rpio');
// var LED_PIN = 29;
// rpio.open(LED_PIN, rpio.OUTPUT,rpio.LOW);

// // 打开LED
// function turnOn() {
// 	rpio.write(LED_PIN, rpio.HIGH);
// }
// // 关闭LED
// function turnOff() {
// 	rpio.write(LED_PIN, rpio.LOW);
// }




router.all('/raspberry/iot', function(req, res, next) {
	var param = req.query || req.params; 
	var status = param.status;
	console.log('status = ',status);
	console.log('status_type = ',typeof(status));
	device.publish('/' + deviceInfo.ProductKey + '/' + deviceInfo.DeviceName +  '/user/update', 'status = ' + status);
	if (status === '1') {  // 开
		res.end(JSON.stringify({
			msg: '开灯成功',
			status: 100,
		}));
	} else { // 关
		res.end(JSON.stringify({
			msg: '关灯成功',
			status: 100,
		}));
	}
})

module.exports = router;
